package com.shanshi.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.shanshi.activity.request.LoginDataBase;
import com.shanshi.activity.response.LoginUserMessage;
import com.shanshi.activity.tool.CustomDialog;
import com.shanshi.activity.tool.OkHttpTool;
import com.shanshi.activity.tool.PhoneNum;

import java.util.HashMap;

import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;

public class LoginActivity extends MainActivity {
	private Button sure;
	private TextView tv;
	private EditText et_num,et_getnum;
	private EventHandler ev;
	private ImageView checkBox;
	private boolean checkState = false;
	private String phoneTypeNum,phoneType,phoneName,phoneModel,tel;
	private double longitude,latitude;
	private SharedPreferences sharedPreferences;
	private SharedPreferences.Editor editor;
	private LoginDataBase loginDataBase=new LoginDataBase();
	private LoginUserMessage loginUserMessage;
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (msg.what == 0) {
				if (msg.arg1 == 0) {
					Toast.makeText(LoginActivity.this,"获取验证码成功", Toast.LENGTH_SHORT).show();
				} else if (msg.arg1 == 1) {
					SMSSDK.unregisterEventHandler(ev);
					tel=et_num.getText().toString();
					editor.putString("phoneNum",tel);
					loginDataBase.setLatitude(latitude);
					loginDataBase.setLongitude(longitude);
					loginDataBase.setPhoneMode(phoneModel);
					loginDataBase.setPhoneName(phoneName);
					loginDataBase.setPhoneType(phoneType);
					loginDataBase.setPhoneTypeNum(phoneTypeNum);
					loginDataBase.setPhoneNum(tel);
					Log.e("phoneinfo", "handleMessage: "+loginDataBase.toString() );
					String request= gson.toJson(loginDataBase);
					OkHttpTool.doPost("http://192.168.28.248:8080/SsProject/app/login", request, new OkHttpTool.setOkhttpListener() {
						@Override
						public void onSuccess(String s) {
							Log.e("userMessage", "onSuccess: "+s );
							loginUserMessage=gson.fromJson(s,LoginUserMessage.class);
							editor.putInt("userId ",loginUserMessage.getData().getId());
							editor.putString("money ", String.valueOf(loginUserMessage.getData().getMoney()));
							editor.putString("shanShiId ", (String) loginUserMessage.getData().getShanShiId());
							editor.putInt("userId ",loginUserMessage.getData().getId());
							editor.putInt("userId ",loginUserMessage.getData().getId());
							if (loginUserMessage.getData().getState()==1){
								Message message = Message.obtain();
								message.what = 0;
								message.arg1 = 3;
								handler.sendMessage(message);
//								Intent nextIntent = new Intent(LoginActivity.this, SpreadMessage.class);
//					            startActivity(nextIntent);
							}else {
								Message message = Message.obtain();
								message.what = 0;
								message.arg1 = 4;
								handler.sendMessage(message);
							}
						}

						@Override
						public void onFail() {
							Log.e("userMessage", "onFail: ");
						}
					});
//					Intent nextIntent = new Intent(LoginActivity.this, SpreadMessage.class);
//					startActivity(nextIntent);
				} else if (msg.arg1 == 2) {
					Toast.makeText(LoginActivity.this,"验证错误", Toast.LENGTH_SHORT).show();
				}else if (msg.arg1==3){
					Intent nextIntent = new Intent(LoginActivity.this, SpreadMessage.class);
					            startActivity(nextIntent);
				}else if (msg.arg1==4){
					showLoginDialog();
				}
			}
		}
	};
	private Gson gson = new Gson();;


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		sharedPreferences=this.getSharedPreferences("share",MODE_PRIVATE);
		editor=sharedPreferences.edit();
		//获取设备号
		TelephonyManager tm =(TelephonyManager)getSystemService(this.TELEPHONY_SERVICE);
		phoneTypeNum=tm.getDeviceId();
		//获取设备类型
		phoneType= android.os.Build.BRAND;
		//获取设备版本号
		phoneModel=android.os.Build.VERSION.RELEASE;
		//获取手机名字
		phoneName=android.os.Build.MODEL;
		//获取经纬度
		longitude= Double.parseDouble(sharedPreferences.getString("userLongitude","0"));
		latitude= Double.parseDouble(sharedPreferences.getString("userLatitude","0"));

		cn.smssdk.SMSSDK.initSDK(this, "1c4cd5652ad16", "89c0c35ad7587a22667379246c29583f");
		sure= (Button) findViewById(R.id.login_sure);
		et_num= (EditText) findViewById(R.id.tel);
		et_getnum= (EditText) findViewById(R.id.verificationCode);
		tv= (TextView) findViewById(R.id.getVerificationCode);
		checkBox= (ImageView) findViewById(R.id.check);
		checkBox.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (!checkState){
					checkBox.setImageResource(R.drawable.check);
					checkState = !checkState;
					sure.setEnabled(true);
					sure.setBackgroundResource(R.drawable.button_style);
				}else {
					checkBox.setImageResource(R.drawable.checkoff);
					checkState = !checkState;
					sure.setEnabled(false);
					sure.setBackgroundResource(R.drawable.button_style5);
				}
			}
		});

		tv.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (PhoneNum.isPhone(et_num.getText().toString())) {
					SMSSDK.getVerificationCode("86", et_num.getText().toString());
					new CountDownTimer(60000, 1000) {
						@Override
						public void onTick(long millisUntilFinished) {
							tv.setText("剩余" + (millisUntilFinished / 1000) + "S");
							tv.setEnabled(false);
						}

						@Override
						public void onFinish() {
							tv.setText("获取验证码");
							tv.setEnabled(true);
						}
					}.start();
				}else {
					Toast.makeText(LoginActivity.this,"请填写正确手机号码",Toast.LENGTH_SHORT).show();
				}
			}
		});
		sure.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				SMSSDK.submitVerificationCode("86",
						et_num.getText().toString(), et_getnum.getText()
								.toString());
				register();

			}
		});
	}

	
	public void nextPage(View view) {
		Intent nextIntent = null;
		switch (view.getId()) {
		case R.id.fanhui:
			finish();
			break;
//		case R.id.login_sure:
//			nextIntent = new Intent(this, SpreadMessage.class);
//		break;
		case R.id.agreement:
			nextIntent = new Intent(this,LoginActivity.class);
			startActivity(nextIntent);
		break;
		}

	}
	private void sendMessage(int what, int arg) {
		Message message = Message.obtain();
		message.what = what;
		message.arg1 = arg;
		handler.sendMessage(message);
	}

	public void showLoginDialog(){
		CustomDialog.Builder builder = new CustomDialog.Builder(this);
        builder.setTitle("系统检测到此帐号已存在，请问您是：");  
        builder.setPositiveButton("新用户", new DialogInterface.OnClickListener() {  
            public void onClick(DialogInterface dialog, int which) {
				Intent nextIntent = new Intent(LoginActivity.this, SpreadMessage.class);
				startActivity(nextIntent);
            }  
        });  
  
        builder.setNegativeButton("现有用户",  
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
						Intent nextIntent = new Intent(LoginActivity.this, AuditInfoActivity.class);
						startActivity(nextIntent);
                    }  
                });  
  
        CustomDialog customDialog = builder.create(R.layout.login_popwindow,R.id.login_title,R.id.login_newuser,R.id.login_olduser,0,0);
        customDialog.show();
        
        //设置弹窗之外的部分不能点击
        customDialog.setCanceledOnTouchOutside(false);
	}
	private void register() {
		ev = new EventHandler() {

			@Override
			public void afterEvent(int event, int result, Object data) {
				if (result == SMSSDK.RESULT_COMPLETE) { // 回调完成
					// 提交验证码成功,如果验证成功会在data里返回数据。data数据类型为HashMap<number,code>
					if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
						Log.e("TAG", "提交验证码成功" + data.toString());
						HashMap<String, Object> mData = (HashMap<String, Object>) data;
						String country = (String) mData.get("country");// 返回的国家编号
						tel = (String) mData.get("phone");// 返回用户注册的手机号
						sendMessage(0,1);
					} else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {// 获取验证码成功
						Log.e("TAG", "获取验证码成功");
						sendMessage(0,0);
					} else if (event == SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES) {// 返回支持发送验证码的国家列表

					}
				} else {
					sendMessage(0,2);
					((Throwable) data).printStackTrace();
				}
			}
		};
		SMSSDK.registerEventHandler(ev); //注册短信回调监听
	}


}
